package com.sy.server.impl;


import com.sy.config.RedisKeyConfig;
import com.sy.dao.SmslogDao;
import com.sy.dto.SmsCodeDto;
import com.sy.entity.Smslog;
import com.sy.server.intf.SmslogService;
import com.sy.third.JedisUtil;
import com.sy.util.NumRandomUtil;
import com.sy.util.StrUtil;
import com.sy.utils.AliSmsUtil;
import com.sy.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class SmslogServiceImpl implements SmslogService {

    @Autowired
    private SmslogDao smslogDao;

    @Override
    public R save(Smslog smslog){
        if(smslogDao.insert(smslog)>0){
            return R.ok();
        }else{
            return R.fail("新增失败");
        }
    }
    @Override
    public R delById(int id){
        if(smslogDao.deleteById(id)>0){
            return R.ok();
        }else{
            return R.fail("删除失败");
        }
    }
    @Override
    public R all(){
       return R.ok(smslogDao.all());
    }

    @Override
    public R sendConde(String phone) {
        //1.校验参数
        if (StrUtil.checkNoEmpty(phone)) {
            //2.正则表达式校验手机号是否正确
            if (phone.matches("[0-9]{11}")) {
                //3.随机生成6位手机验证码
                int code = NumRandomUtil.randomNum(6);
                if (AliSmsUtil.sendSmsCode(phone, code)) {
                    //4.验证码发送成功
                    //5.存储短信验证码，综合考虑使用redis（快，有效期） String
                    JedisUtil.getInstance().addStrEx(RedisKeyConfig.SMS_RCODE+phone, code + "", RedisKeyConfig.SMS_RTIME);
                    //6.记录发送信息
                    smslogDao.insertSms(new Smslog(phone, 1, "发送手机验证码"+code));

                    return R.ok();
                }
            }
        }
        return R.fail("请查看参数");
    }

    @Override
    public R checkCode(SmsCodeDto dto) {
        //校验参数
        if (null != dto) {
            //校验是否为空
            if (StrUtil.checkNoEmpty(dto.getPhone(), dto.getCode()+"")) {
                //获取Key，用户校验
                String key = RedisKeyConfig.SMS_RCODE + dto.getPhone();
                if (JedisUtil.getInstance().ishave(key)) {
                    if (JedisUtil.getInstance().getStr(key).equals(dto.getCode() + "")) {
                        //验证通过
                        //验证码验证只要通过，就删除
                        JedisUtil.getInstance().delKeys(key);
                        return R.ok();
                    }
                }
            }
        }
        return R.fail();
    }
}
